<template>
  <BasicDrawer v-bind="$attrs" @register="register" :title="displayModuleTitle" width="90%">
    <BasicTable
      @register="registerTable"
      title="出入库记录"
      :scroll="{ x: false, y: 'calc(100vh - 300px)' }"
    >
      <template #toolbar>
        <a-button @click="onAddButtonClick" type="primary" v-if="mode == 'add'">入库填单</a-button>
      </template>

      <template #optype="{ record }">
        {{ optypeOptions.filter((item) => item.value == record.optype)[0]?.label }}
      </template>

      <template #action="{ column, record }">
        <TableAction
          :actions="[
            {
              icon: 'ant-design:check-circle-outlined',
              label: '复核',
              color: 'success',
              ifShow: mode == 'check' && !record.checktm,
              popConfirm: {
                title: '是否确认复核？',
                placement: 'left',
                confirm: onCheckButtonClick.bind(null, record),
              },
            },
            {
              icon: 'ant-design:delete-outlined',
              label: '删除',
              color: 'error',
              ifShow: mode == 'add',
              popConfirm: {
                title: '是否确认删除？',
                placement: 'left',
                confirm: onDeleteButtonClick.bind(null, record),
              },
            },
          ]"
        />
        <!-- 复核模式下，已复核的记录显示状态 -->
        <span v-if="mode == 'check' && record.checktm" style="color: #52c41a">
          <Icon icon="ant-design:check-circle-filled" />
          已复核
        </span>
      </template>
    </BasicTable>
    <AddWareHouseInventoryModal
      @register="registerAddWareHouseInventoryModal"
      :optypeOptions="optypeOptions"
      @success="opSuccess"
    />
  </BasicDrawer>
</template>

<script lang="ts">
  import { defineComponent, ref, unref, computed, reactive, onMounted } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { getUnitDivision, queryUnitStaticInfo } from '/@/api/ehs/unitDivision';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { useGlobSetting } from '/@/hooks/setting';
  import AddWareHouseInventoryModal from './AddWareHouseInventoryModal.vue';
  import {
    queryAllWareHouseInventory,
    addWareHouseInventory,
    checkWareHouseInventory,
    deleteWareHouseInventory,
  } from '/@/api/ehs/warehouseInventory';
  import {
    warehouseInventoryRecordColumns,
    queryWareHouseInventoryRecordSchema,
  } from './warehouseInventory.data';
  import { queryEnumOptions } from '/@/api/platform/enum';
  const { globalProjectCode } = useGlobSetting();
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Icon } from '/@/components/Icon';
  const { createMessage } = useMessage();
  export default defineComponent({
    name: 'ViewWareHouseInventoryRecord',
    props: ['mode'],
    components: {
      Icon,
      BasicDrawer,
      BasicTable,
      TableAction,
      AddWareHouseInventoryModal,
    },
    setup(props, { emit }) {
      const operateType = ref(OperationTypeEnum.UN_KNOWN);
      const optypeOptions = ref([]);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const dataId = ref(); // 仓库id
      const projectCode = ref<String>(globalProjectCode);
      const [registerAddWareHouseInventoryModal, { openModal: openAddWareHouseInventoryModal }] =
        useModal();
      const [registerTable, { reload }] = useTable({
        api: queryAllWareHouseInventory,
        columns: warehouseInventoryRecordColumns,
        canResize: true,
        striped: true,
        showTableSetting: false,
        showIndexColumn: true,
        isTreeTable: false,
        bordered: true,
        immediate: false,
        ellipsis: true,
        useSearchForm: true,
        pagination: false,
        formConfig: {
          labelWidth: 60,
          schemas: queryWareHouseInventoryRecordSchema,
        },
        indexColumnProps: {
          width: 50,
        },
        beforeFetch: (params) => {
          params.warehouseid = dataId.value;
          params.begintm = params.tm[0];
          params.endtm = params.tm[1];
          return params;
        },
        actionColumn: {
          width: 150,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });
      /**
       * 过滤出数据对应的枚举类label
       */
      function deepFilter(obj, option, findField1, findField2) {
        for (let i = 0; i < option.length; i++) {
          let a = option[i];
          if (a[findField2] == obj[findField1]) {
            return a;
          } else {
            if (a.children && a.children.length > 0) {
              let res = deepFilter(obj, a.children, findField1, findField2);
              if (res) {
                return res;
              }
            }
          }
        }
        return '-';
      }
      const [register, { closeDrawer, changeLoading }] = useDrawerInner((data) => {
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.operateType) {
            //判断是否传入op属性
            operateType.value = unrefData.operateType;
          }
          dataId.value = data.dataId;
          reload();
        }
      });

      function onCheckButtonClick(record) {
        checkWareHouseInventory(record.id).then((res) => {
          if (!res) {
            opSuccess();
            reload();
            createMessage.success('复核成功!');
          } else {
            createMessage.error('复核失败!');
          }
        });
      }

      function onAddButtonClick() {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '仓库出入库管理',
          operateString: '填单',
          warehouseid: dataId.value,
        };
        openAddWareHouseInventoryModal(true, propsData);
      }

      function onDeleteButtonClick(record) {
        deleteWareHouseInventory(record.id).then((res) => {
          opSuccess();
        });
      }

      function opSuccess() {
        emit('success');
        reload();
      }

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      onMounted(() => {
        queryEnumOptions('EhsWarehouseInventoryOperateTypeEnum').then((res) => {
          optypeOptions.value = res[0].options.map((option) => {
            return {
              value: Number(option.key),
              label: option.value,
            };
          });
        });
      });
      return {
        register,
        registerTable,
        dataId,
        operateType,
        displayModuleTitle,
        qcUnifyProps,
        optypeOptions,
        deepFilter,
        onCheckButtonClick,
        onAddButtonClick,
        registerAddWareHouseInventoryModal,
        onDeleteButtonClick,
        opSuccess,
      };
    },
  });
</script>

<style scoped lang="less"></style>
